package org.wmq.transferordersystem.dao.impl;

import cn.hutool.core.util.IdUtil;
import com.mongodb.client.result.DeleteResult;
import lombok.RequiredArgsConstructor;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;
import org.wmq.transferordersystem.dao.OrderDao;
import org.wmq.transferordersystem.model.Entity.Order;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Repository
@RequiredArgsConstructor
public class OrderDaoImplMongoDB implements OrderDao {
    private final MongoTemplate mongoTemplate;


    @Override
    public Order selectById(Long id) {
        Criteria queryCriteria = Criteria.where("id").is(id);
        return this.mongoTemplate.findOne(new Query(), Order.class);
    }

    @Override
    public void insert(Order order) {
        System.out.println("dao:  " + order);
        order.setId(IdUtil.getSnowflakeNextId());
        order.setStatus("已下单");
        order.setOrderTime(LocalDate.now());
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        this.mongoTemplate.insert(order);
    }

    @Override
    public boolean deleteById(Long id) {
        Criteria queryCriteria = Criteria.where("id").is(id);
        DeleteResult deleteResult = this.mongoTemplate.remove(new Query(queryCriteria), Order.class);
        return deleteResult.getDeletedCount() == 1;
    }

    @Override
    public void updateById(Order order) {

    }

    @Override
    public List<Order> selectAll() {
        return this.mongoTemplate.findAll(Order.class);
    }
}
